import React, { Component } from 'react';
import { connect } from 'dva';
import {Form, FormItem, Input, Select, Button, Upload, Icon, message, Modal, Radio} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import styles from './Add.less';
import request from '@/utils/request';
import { IMG_URL } from '../../utils/utils';

export default
@connect(({ opration,article, loading }) => ({
  opration,
  article,
  submitting: loading.effects['opration/save'],
}))
@Form.create()
class BannerEdit extends Component {
  state = {
    preview: '',
    visible: false,
    imageList: [],
    categoryList:[]
  };
  componentDidMount() {
    const oprationId = this.props.match.params.id;
    const {dispatch} = this.props;
    dispatch({
      type: 'opration/detail',
      payload: oprationId
    });
    dispatch({
      type: 'article/fetchCategory',
      payload: { type: 'activity' },
    });
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.opration.detail && nextProps.opration.detail.id) {
      this.setState({
        id: nextProps.opration.detail.id,
        name:nextProps.opration.detail.name,
        type: nextProps.opration.detail.type,
        category: nextProps.opration.detail.category,
        url: nextProps.opration.detail.url,
        imageList: [{
          uid: 1,
          name: "name",
          status: "200",
          type: "type",
          result: "fileName",
          url: nextProps.opration.detail.pic,
        }],
      })
    }
  }
  beforeUpload = file => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      request('/api/oss/sign/images', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;',
        },
      }).then(OSSSign => {
        let timestamp3 = new Date().getTime();
        const xhr = new XMLHttpRequest();
        let ossData = new FormData();
        ossData.append('name', file.name);
        ossData.append('OSSAccessKeyId', OSSSign.accessId);
        ossData.append('policy', OSSSign.policy);
        ossData.append('Signature', OSSSign.signature);
        ossData.append('callback', OSSSign.callback);
        ossData.append('key', `${OSSSign.dir}${OSSSign.policy.substr(0, 16)}${file.name}`);
        ossData.append('success_action_status', "200"); // 指定返回的状态码
        ossData.append('file', file);
        xhr.open('POST', OSSSign.host);
        xhr.send(ossData);
        xhr.addEventListener('load', () => {
          console.log('response==>' + xhr.responseText);
          const response = JSON.parse(xhr.responseText);
          if (response.filename) {
            this.setState(({ imageList }) => ({
              imageList: [{
                uid: file.uid,
                name: file.name,
                status: file.status,
                type: file.type,
                result: file.name,
                url: IMG_URL + response.filename,
              }],
            }));
          } else {
            alert('服务器异常');
          }
        });
        xhr.addEventListener('error', () => {
          alert('服务器异常');
        });
      });
    };
    return false;
  };

  handlePreview = (file) => {
    this.setState({
      preview: file.url || file.thumbUrl,
      visible: true,
    });
  };
  handleCancel=()=>{
    this.setState({
      visible: false,
    });
  }
  addAdvert = () => {
    const { dispatch, form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        dispatch({
          type: 'opration/save',
          payload: {
            id:this.state.id,
            type:"焦点图",
            pic: this.state.imageList[0].url,
            ...values,
          },
        });
      }
    });
  };
  render() {
    const propsImgs = {
      onRemove: (file) => {
        this.setState(({ imageList }) => {
          const index = imageList.indexOf(file);
          const newFileList = imageList.slice();
          newFileList.splice(index, 1);
          return { imageList: newFileList };
        });
      },
      beforeUpload: this.beforeUpload,
      fileList: this.state.imageList,
      onPreview: this.handlePreview,
      accept: 'image/*',
      listType: 'picture-card',
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;
    const { preview, visible, imageList } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <PageHeaderWrapper
        title="编辑焦点图"
      >
        <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
          <Form.Item {...formItemLayout} label="活动类别">
            {getFieldDecorator('category', {
              initialValue:this.state.category ,
              rules: [
                {
                  required: true,
                  message: '请选择活动类别',
                },
              ],
            })(<Select>
              <Select.Option value="阅读时光">阅读时光</Select.Option>
              <Select.Option value="星空讲堂">星空讲堂</Select.Option>
            </Select>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="标题">
            {getFieldDecorator('name', {
              initialValue:this.state.name ,
              rules: [
                {
                  required: true,
                  message: '标题不能为空',
                },
              ],
            })(<Input placeholder="请输入标题"/>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="url链接">
            {getFieldDecorator('url', {
              initialValue:this.state.url,
              rules: [
                {
                  required: true,
                  message: 'url链接不能为空',
                },
              ],
            })(<Input placeholder="请输入url链接"/>)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="封面图">
            <div>
              <Upload {...propsImgs}>
                {
                  imageList.length >= 1 ? null : uploadButton
                }
              </Upload>
              <Modal visible={visible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={preview}/>
              </Modal>
            </div>
          </Form.Item>
          <Form.Item {...formItemLayout} label="操作">
            <Button type="primary" onClick={() => this.addAdvert()}>
              提交
            </Button>
          </Form.Item>
        </Form>
      </PageHeaderWrapper>
    );
  }
}
